<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item 
        label="商家名称" 
        prop="merchantId" 
        class="form-item"
        required
      >
        <el-select 
          v-model="formData.merchantId" 
          placeholder="请选择商家" 
          filterable 
          :loading="merchantLoading"
          class="w-full"
          popper-class="merchant-select-dropdown"
          clearable
          @focus="handleMerchantSelectFocus"
          @visible-change="handleMerchantVisibleChange"
          @filter-method="handleMerchantSearch"
        >
          <el-option
            v-for="item in merchantList"
            :key="item.id"
            :label="item.merchantName"
            :value="item.id"
          />
          <template #dropdown>
            <div class="merchant-select-content">
              <div v-if="merchantList.length === 0" class="merchant-empty">
                <el-empty description="暂无数据" />
              </div>
              <div v-if="merchantHasMore && !merchantLoading" class="merchant-loading">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span class="loading-text">加载更多...</span>
              </div>
            </div>
          </template>
        </el-select>
      </el-form-item>
     
      <el-form-item label="授信类型" prop="creditType">
        <el-radio-group v-model="formData.creditType">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.JULIANG_CREDIT_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item 
        v-if="formData.creditType === 1"
        label="授信额度" 
        prop="creditAmount"
      >
        <el-input v-model="formData.creditAmount" placeholder="请输入授信额度" />
      </el-form-item>
      <el-form-item 
        v-if="formData.creditType === 2"
        label="授信比例" 
        prop="creditRatio"
      >
        <el-input v-model="formData.creditRatio" placeholder="请输入授信比例" />
      </el-form-item>
     
      <el-form-item label="授信状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { MerchantCreditApi, MerchantCreditVO } from '@/api/juliang/merchantcredit'
import { MerchantApi, MerchantVO } from '@/api/juliang/merchant'
import { MerchantBankApi } from '@/api/juliang/merchantbank'
import { Loading } from '@element-plus/icons-vue'
import { throttle, debounce } from 'lodash-es'

/** 商家授信管理 表单 */
defineOptions({ name: 'MerchantCreditForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 商家相关
const merchantList = ref<MerchantVO[]>([]) // 商家列表
const merchantLoading = ref(false) // 商家列表加载状态
const merchantHasMore = ref(true) // 是否还有更多数据
const merchantLoadingNewPage = ref(false) // 标记是否正在加载新页面
const merchantSearchKeyword = ref('') // 搜索关键字

const merchantQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantName: undefined as string | undefined
})

// 账户相关
const accountList = ref<any[]>([]) // 账户列表
const accountLoading = ref(false) // 账户列表加载状态
const accountHasMore = ref(true) // 是否还有更多数据
const accountLoadingNewPage = ref(false) // 标记是否正在加载新页面
const accountSearchKeyword = ref('') // 搜索关键字

const accountQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  accountName: undefined as string | undefined,
  merchantId: undefined as number | undefined
})

const formData = ref<{
  id: number | undefined
  merchantId: number | undefined
  accountId: number | undefined
  creditType: number | undefined
  creditAmount: number | undefined
  creditRatio: number | undefined
  status: number | undefined
}>({
  id: undefined,
  merchantId: undefined,
  accountId: undefined,
  creditType: undefined,
  creditAmount: undefined,
  creditRatio: undefined,
  status: undefined,
})

const formRules = reactive({
  merchantId: [{ required: true, message: '商家不能为空', trigger: 'change' }],
  accountId: [{ required: true, message: '账户不能为空', trigger: 'change' }],
  creditType: [{ required: true, message: '授信类型不能为空', trigger: 'change' }],
  creditAmount: [{ required: true, message: '授信额度不能为空', trigger: 'blur' }],
  creditRatio: [{ required: true, message: '授信比例不能为空', trigger: 'blur' }],
})

const formRef = ref() // 表单 Ref

/** 获取商家列表 */
const getMerchantList = async (isLoadMore = false) => {
  if (merchantLoading.value || (isLoadMore && !merchantHasMore.value)) return
  
  if (isLoadMore) {
    merchantLoadingNewPage.value = true
  } else {
    merchantLoading.value = true
  }

  try {
    const data = await MerchantApi.getMerchantPage({
      pageNo: merchantQuery.pageNo,
      pageSize: merchantQuery.pageSize,
      merchantName: merchantSearchKeyword.value
    })
    
    if (data?.list?.length > 0) {
      // 如果是编辑状态，确保当前选中的商家保留在列表中
      if (isLoadMore && formType.value === 'update' && formData.value.merchantId) {
        const currentMerchant = merchantList.value.find(item => item.id === formData.value.merchantId)
        if (currentMerchant) {
          merchantList.value = [
            currentMerchant,
            ...merchantList.value.filter(item => item.id !== currentMerchant.id),
            ...data.list.filter(item => item.id !== currentMerchant.id)
          ]
        } else {
          merchantList.value = [...merchantList.value, ...data.list]
        }
      } else {
        merchantList.value = isLoadMore 
          ? [...merchantList.value, ...data.list]
          : data.list
      }
      merchantHasMore.value = data.list.length === merchantQuery.pageSize
    } else {
      if (!isLoadMore) {
        // 如果是编辑状态，保留当前选中的商家
        if (formType.value === 'update' && formData.value.merchantId) {
          const currentMerchant = merchantList.value.find(item => item.id === formData.value.merchantId)
          merchantList.value = currentMerchant ? [currentMerchant] : []
        } else {
          merchantList.value = []
        }
      }
      merchantHasMore.value = false
    }
  } catch (error) {
    console.error('获取商家列表失败:', error)
    message.error('获取商家列表失败')
    if (!isLoadMore) {
      merchantList.value = []
    }
  } finally {
    merchantLoading.value = false
    merchantLoadingNewPage.value = false
  }
}

/** 获取账户列表 */
const getAccountList = async (isLoadMore = false) => {
  if (accountLoading.value || (isLoadMore && !accountHasMore.value)) return
  
  if (isLoadMore) {
    accountLoadingNewPage.value = true
  } else {
    accountLoading.value = true
  }

  try {
    const data = await MerchantBankApi.getMerchantBankPage({
      pageNo: accountQuery.pageNo,
      pageSize: accountQuery.pageSize,
      accountName: accountSearchKeyword.value,
      merchantId: formData.value.merchantId // 只获取当前选中商家的账户
    })
    
    if (data?.list?.length > 0) {
      // 如果是编辑状态，确保当前选中的账户保留在列表中
      if (isLoadMore && formType.value === 'update' && formData.value.accountId) {
        const currentAccount = accountList.value.find(item => item.id === formData.value.accountId)
        if (currentAccount) {
          accountList.value = [
            currentAccount,
            ...accountList.value.filter(item => item.id !== currentAccount.id),
            ...data.list.filter(item => item.id !== currentAccount.id)
          ]
        } else {
          accountList.value = [...accountList.value, ...data.list]
        }
      } else {
        accountList.value = isLoadMore 
          ? [...accountList.value, ...data.list]
          : data.list
      }
      accountHasMore.value = data.list.length === accountQuery.pageSize
    } else {
      if (!isLoadMore) {
        // 如果是编辑状态，保留当前选中的账户
        if (formType.value === 'update' && formData.value.accountId) {
          const currentAccount = accountList.value.find(item => item.id === formData.value.accountId)
          accountList.value = currentAccount ? [currentAccount] : []
        } else {
          accountList.value = []
        }
      }
      accountHasMore.value = false
    }
  } catch (error) {
    console.error('获取账户列表失败:', error)
    message.error('获取账户列表失败')
    if (!isLoadMore) {
      accountList.value = []
    }
  } finally {
    accountLoading.value = false
    accountLoadingNewPage.value = false
  }
}

/** 监听商家下拉框滚动 */
const handleMerchantDropdownScroll = throttle(async (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  if (scrollHeight - scrollTop - clientHeight < 50 && merchantHasMore.value && !merchantLoadingNewPage.value) {
    merchantQuery.pageNo++
    await getMerchantList(true)
  }
}, 200)

/** 监听账户下拉框滚动 */
const handleAccountDropdownScroll = throttle(async (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  if (scrollHeight - scrollTop - clientHeight < 50 && accountHasMore.value && !accountLoadingNewPage.value) {
    accountQuery.pageNo++
    await getAccountList(true)
  }
}, 200)

/** 处理商家下拉框显示状态变化 */
const handleMerchantVisibleChange = (visible: boolean) => {
  if (visible) {
    nextTick(() => {
      const dropdownWrapper = document.querySelector('.merchant-select-dropdown .el-select-dropdown__wrap')
      if (dropdownWrapper) {
        dropdownWrapper.addEventListener('scroll', handleMerchantDropdownScroll)
      }
    })
  } else {
    const dropdownWrapper = document.querySelector('.merchant-select-dropdown .el-select-dropdown__wrap')
    if (dropdownWrapper) {
      dropdownWrapper.removeEventListener('scroll', handleMerchantDropdownScroll)
    }
  }
}

/** 处理账户下拉框显示状态变化 */
const handleAccountVisibleChange = (visible: boolean) => {
  if (visible) {
    nextTick(() => {
      const dropdownWrapper = document.querySelector('.account-select-dropdown .el-select-dropdown__wrap')
      if (dropdownWrapper) {
        dropdownWrapper.addEventListener('scroll', handleAccountDropdownScroll)
      }
    })
  } else {
    const dropdownWrapper = document.querySelector('.account-select-dropdown .el-select-dropdown__wrap')
    if (dropdownWrapper) {
      dropdownWrapper.removeEventListener('scroll', handleAccountDropdownScroll)
    }
  }
}

/** 处理商家搜索 */
const handleMerchantSearch = debounce((query: string) => {
  merchantSearchKeyword.value = query.trim()
  merchantQuery.pageNo = 1
  merchantHasMore.value = true
  merchantList.value = []
  getMerchantList()
}, 300)

/** 处理账户搜索 */
const handleAccountSearch = debounce((query: string) => {
  accountSearchKeyword.value = query.trim()
  accountQuery.pageNo = 1
  accountHasMore.value = true
  accountList.value = []
  getAccountList()
}, 300)

/** 处理商家下拉框获得焦点 */
const handleMerchantSelectFocus = () => {
  if (merchantList.value.length === 0) {
    merchantSearchKeyword.value = ''
    merchantQuery.pageNo = 1
    merchantHasMore.value = true
    getMerchantList()
  }
}

/** 处理账户下拉框获得焦点 */
const handleAccountSelectFocus = () => {
  if (accountList.value.length === 0 && formData.value.merchantId) {
    accountSearchKeyword.value = ''
    accountQuery.pageNo = 1
    accountHasMore.value = true
    getAccountList()
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  formLoading.value = true
  try {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    
    if (type === 'create') {
      // 新增时设置默认值
      formData.value.creditType = 0 // 无授信
      formData.value.status = 0 // 开启
      formLoading.value = false
      return
    }
    
    // 修改时，获取数据
    if (id) {
      const data = await MerchantCreditApi.getMerchantCreditById(id)
      formData.value = data
      
      // 如果有商家ID，获取商家详情
      if (data.merchantId) {
        const merchantDetail = await MerchantApi.getMerchantById(data.merchantId)
        if (merchantDetail) {
          merchantList.value = [merchantDetail]
          await getMerchantList()
        }
      }
      
      // 如果有账户ID，获取账户列表
      if (data.accountId) {
        await getAccountList()
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    merchantId: undefined,
    accountId: undefined,
    creditType: undefined,
    creditAmount: undefined,
    creditRatio: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
  // 重置商家相关的状态
  merchantList.value = []
  merchantHasMore.value = true
  merchantQuery.pageNo = 1
  merchantSearchKeyword.value = ''
  // 重置账户相关的状态
  accountList.value = []
  accountHasMore.value = true
  accountQuery.pageNo = 1
  accountSearchKeyword.value = ''
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      // 根据授信类型清除不需要的字段
      creditAmount: formData.value.creditType === 1 ? formData.value.creditAmount : undefined,
      creditRatio: formData.value.creditType === 2 ? formData.value.creditRatio : undefined,
    }
    
    if (formType.value === 'create') {
      await MerchantCreditApi.createMerchantCredit(data as unknown as MerchantCreditVO)
      message.success(t('common.createSuccess'))
    } else {
      await MerchantCreditApi.updateMerchantCredit(data as unknown as MerchantCreditVO)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 监听商家ID变化，当商家ID变化时，清空并重新加载账户列表
watch(() => formData.value.merchantId, (newVal) => {
  formData.value.accountId = undefined
  accountList.value = []
  accountHasMore.value = true
  accountQuery.pageNo = 1
  accountSearchKeyword.value = ''
  if (newVal) {
    getAccountList()
  }
})

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

<style lang="scss" scoped>
.merchant-select-content,
.account-select-content {
  .merchant-empty,
  .account-empty {
    padding: 20px;
    text-align: center;
  }
  
  .merchant-loading,
  .account-loading {
    padding: 8px 0;
    text-align: center;
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
      color: var(--el-color-primary);
      vertical-align: middle;
    }
    
    .loading-text {
      font-size: 13px;
      color: var(--el-text-color-secondary);
      vertical-align: middle;
    }
  }
}

:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-select-dropdown__list) {
  padding: 0;
}

.w-full {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
  
  &:last-child {
    margin-bottom: 0;
  }
}
</style>